package com.yc.yyds.biz;

import com.yc.yyds.dao.SaveIndentDao;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Map;

public class SaveIndentBiz {
    SaveIndentDao dao = new SaveIndentDao();
    public void save(String userid,String ppjhid,String num,String seats,String money,String balance) throws BizException {
        if (ppjhid.isEmpty() ||userid.isEmpty()||num.isEmpty()||seats.isEmpty()||money.isEmpty()){
            throw new BizException("业务异常");
        }
        if (Integer.parseInt(balance)<Integer.parseInt(money)){
            throw new BizException("余额不足!");
        }
        try {
            //存
            dao.saveIndent(userid,ppjhid,seats,money);
        }catch (Exception e){
            throw new BizException(e.getMessage());
        }
    }
    //确认订单
    public void queren(String userid,String ppjhid,String num,String balance,String money,String indentid,String payway) throws BizException {
        //查余票
        String ticksnum = dao.countSeat(ppjhid).get("remainseats").toString();
        if (Integer.parseInt(ticksnum)<Integer.parseInt(num)) {
            throw new BizException("余票不足");
        }
        //改余票
        dao.updateIndent(ppjhid,(Integer.parseInt(ticksnum)-Integer.parseInt(num)));
        //改余额
        if (payway.equals("1")){
            float qian = Float.parseFloat(balance)-Float.parseFloat(money);
            dao.updataUserMoney(userid,qian);
        }
        //改支付状态
        dao.queren(indentid);
    }

    //查找座位
    public List<Integer> find(String ppjhid) throws BizException {
        try {
            List<Map<String, Object>> list = dao.querySeats(ppjhid);
            List<Integer> seats = new ArrayList<>();
            for (Map<String, Object> map : list) {
                String[] split = map.get("seat").toString().split("\\D[\\s]*");
                for (int i = 0; i < split.length; i+=2) {
                    int seat = ((Integer.parseInt(split[i]) - 1) * 5 + Integer.parseInt(split[i + 1]));
                    seats.add(seat);
                }
            }
            return seats;
        }catch (Exception e){
            throw new BizException("业务异常，请联系管理员");
        }
    }
    //查订单信息
    public Map<String,Object> query() throws BizException {
        try {
            return dao.query();
        }catch (Exception e){
            throw new BizException("业务繁忙,稍后再试");
        }
    }
}
